import React, { useState, memo } from 'react';
import { Card, Tag, Space, Typography, Button, Badge, Dropdown, message } from 'antd';
import type { MenuProps } from 'antd';
import {
  FireOutlined,
  EyeOutlined,
  StarOutlined,
  StarFilled,
  EditOutlined,
  ShareAltOutlined,
  CopyOutlined,
  LinkOutlined,
} from '@ant-design/icons';
import { HotItemBase } from '../../../types/hotRadar';
import { platformConfig } from '../../../constants/platforms';
import { useHotRadarStore } from '../../../stores/hotRadar.store';
import { useBreakpoint } from '../../../hooks/useBreakpoint';
import { useLongPress } from '../../../hooks/useLongPress';
import './style.css';

const { Title, Text, Paragraph } = Typography;

interface HotItemCardProps {
  item: HotItemBase;
  onClick?: (item: HotItemBase) => void;
  onCreateClick?: (item: HotItemBase) => void;
}

export const HotItemCard: React.FC<HotItemCardProps> = memo(({ item, onClick, onCreateClick }) => {
  const { favoriteIds, toggleFavorite } = useHotRadarStore();
  const isFavorited = favoriteIds.includes(item.item_id);
  const breakpoint = useBreakpoint();
  const isMobile = breakpoint === 'mobile';
  const [contextMenuOpen, setContextMenuOpen] = useState(false);

  const platformInfo = platformConfig[item.platform] || {
    name: item.platform,
    color: 'default',
    icon: null,
  };

  const handleFavoriteClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    toggleFavorite(item.item_id);
  };

  const handleCreateClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    // 如果有自定义创作处理函数，使用它；否则跳转到编辑器
    if (onCreateClick) {
      onCreateClick(item);
    } else {
      // 默认行为：跳转到编辑器
      window.location.href = `/editor?hotItemId=${item.item_id}`;
    }
  };

  const formatHeatValue = (value: string): string => {
    const num = parseInt(value);
    if (num >= 100000000) {
      return `${(num / 100000000).toFixed(1)}亿`;
    }
    if (num >= 10000) {
      return `${(num / 10000).toFixed(1)}万`;
    }
    return value;
  };

  // 长按显示快捷菜单
  const handleLongPress = () => {
    if (isMobile) {
      setContextMenuOpen(true);
    }
  };

  // 快捷菜单项
  const menuItems: MenuProps['items'] = [
    {
      key: 'favorite',
      icon: isFavorited ? <StarFilled style={{ color: '#faad14' }} /> : <StarOutlined />,
      label: isFavorited ? '取消收藏' : '添加收藏',
      onClick: () => {
        toggleFavorite(item.item_id);
        setContextMenuOpen(false);
      },
    },
    {
      key: 'create',
      icon: <EditOutlined />,
      label: '创作内容',
      onClick: () => {
        handleCreateClick({} as React.MouseEvent);
        setContextMenuOpen(false);
      },
    },
    {
      key: 'share',
      icon: <ShareAltOutlined />,
      label: '分享',
      onClick: () => {
        if (navigator.share) {
          navigator.share({
            title: item.title,
            text: item.excerpt || item.title,
            url: item.url,
          });
        } else {
          message.info('浏览器不支持分享功能');
        }
        setContextMenuOpen(false);
      },
    },
    {
      key: 'copy',
      icon: <CopyOutlined />,
      label: '复制标题',
      onClick: () => {
        navigator.clipboard.writeText(item.title);
        message.success('已复制到剪贴板');
        setContextMenuOpen(false);
      },
    },
    {
      key: 'link',
      icon: <LinkOutlined />,
      label: '复制链接',
      onClick: () => {
        navigator.clipboard.writeText(item.url);
        message.success('已复制链接');
        setContextMenuOpen(false);
      },
    },
  ];

  // 长按手势
  const longPressHandlers = useLongPress({
    onLongPress: handleLongPress,
    onClick: () => onClick?.(item),
    delay: 500,
  });

  const cardContent = (
    <Card
      className={`hot-item-card ${isMobile ? 'hot-item-card-mobile touch-feedback' : ''}`}
      hoverable
      onClick={() => onClick?.(item)}
      {...(isMobile ? longPressHandlers : {})}
      actions={[
          <Button
            key="favorite"
            type="text"
            icon={isFavorited ? <StarFilled style={{ color: '#faad14' }} /> : <StarOutlined />}
            onClick={handleFavoriteClick}
            className={isMobile ? 'h-11 min-w-[44px]' : ''}
          >
            {!isMobile && (isFavorited ? '已收藏' : '收藏')}
          </Button>,
          <Button
            key="create"
            type="text"
            icon={<EditOutlined />}
            onClick={handleCreateClick}
            className={isMobile ? 'h-11 min-w-[44px]' : ''}
          >
            {!isMobile && '创作'}
          </Button>,
          <Button
            key="view"
            type="text"
            icon={<EyeOutlined />}
            className={isMobile ? 'h-11 min-w-[44px]' : ''}
          >
            {!isMobile && '查看'}
          </Button>,
        ]}
      >
        <div className="hot-item-card-header">
          <Tag color={platformInfo.color} className={isMobile ? 'text-xs' : ''}>
            {platformInfo.icon} {platformInfo.name}
          </Tag>
          {item.category && (
            <Tag color="default" className={isMobile ? 'text-xs' : ''}>{item.category}</Tag>
          )}
        </div>

        <div className={`hot-item-card-body ${isMobile ? 'space-y-2' : 'space-y-3'}`}>
          <Title
            level={5}
            ellipsis={{ rows: 2 }}
            className={isMobile ? 'text-sm' : ''}
          >
            {item.title}
          </Title>

          {item.excerpt && (
            <Paragraph
              ellipsis={{ rows: isMobile ? 2 : 3 }}
              className={`hot-item-excerpt ${isMobile ? 'text-xs' : 'text-sm'}`}
            >
              {item.excerpt}
            </Paragraph>
          )}

          <div className="hot-item-stats">
            <Space size={isMobile ? 'small' : 'middle'}>
              <span className={`heat-value ${isMobile ? 'text-xs' : 'text-sm'}`}>
                <FireOutlined style={{ color: '#ff4d4f' }} />
                {' '}热度: {formatHeatValue(item.heat_value)}
              </span>
            </Space>
          </div>

          <div className="hot-item-time">
            <Text type="secondary" className={isMobile ? 'text-xs' : 'text-sm'}>
              更新于: {new Date(item.updated_at).toLocaleString('zh-CN', {
                month: 'numeric',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
              })}
            </Text>
          </div>
        </div>
    </Card>
  );

  return (
    <Badge.Ribbon
      text={`#${item.rank}`}
      color={item.rank <= 3 ? 'red' : 'blue'}
    >
      {isMobile ? (
        <Dropdown
          menu={{ items: menuItems }}
          trigger={['contextMenu']}
          open={contextMenuOpen}
          onOpenChange={setContextMenuOpen}
        >
          {cardContent}
        </Dropdown>
      ) : (
        cardContent
      )}
    </Badge.Ribbon>
  );
});